<template>
  <div>
    <el-breadcrumb separator="/" style="padding-left:10px;padding-bottom:10px;font-size:12px;">
      <el-breadcrumb-item :to="{ path: '/main' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>系统管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 用户列表卡片区 -->
    <el-card>
      <el-form :inline="true" :model="userVo" class="demo-form-inline">
        <el-form-item label="部门" label-width="70px">
          <el-select clearable v-model="userVo.departmentId" placeholder="请选择">
            <el-option
              v-for="item in departments"
              :key="item.id"
              :label="item.name"
              :value="item.id">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
              <span class="el-tag el-tag--success el-tag--mini el-tag--plain">{{ item.deptCount }}</span>
            </span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户名" label-width="70px">
          <el-input clearable v-model="userVo.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" label-width="70px">
          <el-input clearable v-model="userVo.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label-width="70px" style="margin-left: 25px">
          <el-radio v-model="userVo.sex" label="0">帅哥</el-radio>
          <el-radio v-model="userVo.sex" label="1">美女</el-radio>
          <el-radio v-model="userVo.sex" label="">全部</el-radio>
        </el-form-item>
        <el-form-item label="昵称" label-width="70px">
          <el-input clearable v-model="userVo.nickname" placeholder="请输入昵称"></el-input>
        </el-form-item>
        <el-form-item style="margin-left: 10px">
          <el-button icon="el-icon-refresh" @click="resetUserVo">重置</el-button>
          <el-button type="primary" icon="el-icon-search" @click="getUserList">查询</el-button>
          <el-button type="success" icon="el-icon-plus" @click="show">添加</el-button>
          <el-button type="warning" icon="el-icon-download" @click="exportExcel">导出</el-button>
        </el-form-item>
      </el-form>
      <!--表格-->
      <el-table
        :data="userList"
        border
        max-height="100%"
        style="width: 100%;">
        <el-table-column
          prop="id"
          label="#"
          width="50">
        </el-table-column>
        <el-table-column
          prop="username"
          label="用户名"
          width="110">
        </el-table-column>
        <el-table-column
          prop="sex"
          label="性别"
          width="60">
          <template slot-scope="scope">
            <span class="el-tag el-tag--success el-tag--mini el-tag--light">{{scope.row.sex==0?'帅哥':(scope.row.sex==1?'美女':'保密')}}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="name"
          sortable
          label="所属部门"
          width="180">
        </el-table-column>
        <el-table-column
          sortable
          prop="birth"
          label="生日"
          width="180">
          <template slot-scope="scope">
            {{scope.row.birth}}
          </template>
        </el-table-column>
        <el-table-column
          sortable
          prop="email"
          label="邮箱"
          width="180">
        </el-table-column>
        <el-table-column
          prop="phoneNumber"
          label="电话"
          width="150">
        </el-table-column>
        <el-table-column
          prop="status"
          label="是否禁用"
          width="100">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status==1"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scop">
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="edit(scop.row.id)"></el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete" @click="del(scop.row.id)"></el-button>
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-s-tools"
                @click="assignRoles(scop.row.id)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="padding-top: 15px"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"

        :current-page="current"
        :page-sizes="[6, 10, 20, 30,60]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
      <UserAdd :addOrUpdateVisible="addOrUpdateVisible" :departments="departments" @getUserList="getUserList" @getDeptAndCount="getDeptAndCount" @changeShow="showAddOrUpdate" ref="addOrUpdateRef"></UserAdd>
      <!-- 修改对话框 -->
      <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editClose">
        <span>
          <el-form
            :model="editForm"
            :label-position="labelPosition"
            :rules="addFormRules"
            ref="editFormRef"
            label-width="80px"
          >
            <el-row>
              <el-col :span="10">
                <div class="grid-content bg-purple">
                  <el-form-item label="用户名" prop="username">
                    <el-input v-model="editForm.username" :disabled="true"></el-input>
                    <el-input
                      type="hidden"
                      v-model="editForm.id"
                      :disabled="true"
                      style="display:none;"
                    ></el-input>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="grid-content bg-purple-light">
                  <el-form-item label="部门" prop="departmentId">
                    <el-select v-model="editForm.departmentId" placeholder="请选择所属部门">
                      <el-option
                        v-for="department in departments"
                        :key="department.id"
                        :label="department.name"
                        :value="department.id"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="10">
                <div class="grid-content bg-purple">
                  <el-form-item label="昵称" prop="nickname">
                    <el-input v-model="editForm.nickname"></el-input>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="grid-content bg-purple-light">
                  <el-form-item label="性别" prop="sex">
                    <el-radio-group v-model="editForm.sex">
                      <el-radio :label="0">帅哥</el-radio>
                      <el-radio :label="1">美女</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>

            <el-form-item label="邮箱" prop="email">
              <el-input v-model="editForm.email"></el-input>
            </el-form-item>
            <el-form-item label="联系方式" prop="phoneNumber">
              <el-input v-model="editForm.phoneNumber"></el-input>
            </el-form-item>
            <el-form-item prop="birth" label="生日">
              <el-col :span="11">
                <el-date-picker
                  value-format="yyyy-MM-dd"
                  placeholder="选择出生日期"
                  v-model="editForm.birth"
                  style="width: 100%;"
                  clearable
                ></el-date-picker>
              </el-col>
            </el-form-item>
          </el-form>
        </span>

        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="updateUser"
            :loading="btnLoading"
            :disabled="btnDisabled"
          >确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配角色对话框 -->
      <el-dialog center title="分配角色" :visible.sync="assignDialogVisible" width="49%">
        <span>
          <template>
            <el-transfer
              filterable
              filter-placeholder="请输入角色名称"
              :titles="['未拥有','已拥有']"
              :button-texts="['到左边', '到右边']"
              v-model="value1"
              :props="{
                key : 'id',
                label : 'roleName'
              }"
              :data="data1"
              @change="handleChange"
            ></el-transfer>
          </template>
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="assignDialogVisible = false" class="el-icon-close">取消分配</el-button>
          <el-button
            type="primary"
            @click="doAssignRoles"
            class="el-icon-check"
            :loading="btnLoading"
            :disabled="btnDisabled"
          >确定分配</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import {
  findUserList,
  exportUserInfo,
  deleteUser,
  userInfoDetail,
  updateUserInfo,
  findRolePage,
  bindUserRole, getRoleByUserId
} from '../../../api/Users'
  import { findDeptAndCount } from '../../../api/dept'
  import UserAdd from './UserAdd'

export default {
  name: 'vueUsers',
  data() {
    //邮箱校验规则
    var checkEmail = (rule, value, callback) => {
      const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
      if (!value) {
        return callback(new Error("邮箱不能为空"));
      }
      setTimeout(() => {
        if (mailReg.test(value)) {
          callback();
        } else {
          callback(new Error("请输入正确的邮箱格式"));
        }
      }, 100);
    };
    //手机号检验规则
    var checkPhone = (rule, value, callback) => {
      const phoneReg = /^1[34578]\d{9}$$/;
      if (!value) {
        return callback(new Error("电话号码不能为空"));
      }
      setTimeout(() => {
        // Number.isInteger是es6验证数字是否为整数的方法,实际输入的数字总是识别成字符串
        // 所以在前面加了一个+实现隐式转换

        if (!Number.isInteger(+value)) {
          callback(new Error("请输入数字值"));
        } else {
          if (phoneReg.test(value)) {
            callback();
          } else {
            callback(new Error("电话号码格式不正确"));
          }
        }
      }, 100);
    };
    return {
      roleVo:{
        roleName:'',
        remark:''
      },//默认角色查询条件为空
      userRole:{
        userId:'',
        roleId:''
      },
      data1:[],
      value1:[],
      userVo: {
        departmentId: '',
        username: '',
        email: '',
        sex: '',
        nickname: '',
      },
      btnLoading: false,
      btnDisabled: false,
      // 控制新增编辑弹窗的显示与隐藏
      addOrUpdateVisible: false, //添加对话框
      editDialogVisible:false,   //修改对话框
      labelPosition: "right", //lable对齐方式
      assignDialogVisible: false, //分配角色对话框
      //用户集合
        userList: [],
      //部门集合
      deptList: [],
      //每页显示的条数
      size: 6,
      //总条数
      total: 100,
      //当前页码
      current: 1,
      departments: [],
      editForm: {}, //更新表单
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 3, max: 12, message: "长度在 3 到 12 个字符", trigger: "blur" }
        ],
        departmentId: [
          { required: true, message: "请选择部门", trigger: "blur" }
        ],
        sex: [{ required: true, message: "请选择性别", trigger: "blur" }],
        birth: [{ required: true, message: "请填写出生日期", trigger: "blur" }],
        email: [{ required: true, validator: checkEmail, trigger: "blur" }],
        phoneNumber: [
          {
            required: true,
            validator: checkPhone,
            trigger: "blur"
          }
        ],
        nickname: [
          { required: true, message: "请输入昵称", trigger: "blur" },
          { min: 5, max: 10, message: "长度在 5 到 10 个字符", trigger: "blur" }
        ]
      }, //添加表单验证规则
      roles: [], //角色
      value: []//用户拥有的角色

    }
  },
  components: {
    UserAdd,
  },
  created () {
    // 创建组件的时候调用查询所有用户的方法
    this.getDeptAndCount()
    this.getUserList()
  },
  methods: {
    onSubmit () {
      console.log('submit!')
    },
    //当每页条数改变的时候
    handleSizeChange (val) {
      //将val赋值到size
      this.size = val;
      //重新到后台查询
      this.getUserList();
    },
    //当前页码改变的时候
    handleCurrentChange (val) {
      this.current=val;
      this.getUserList();
    },
    async getUserList () {
      const { data } = await findUserList(this.current,this.size,this.userVo)
      this.userList = data.data.records;
      this.total = data.data.total;
      //userList根据departmentId取departments中的姓名
      // this.userList.forEach(item => {
      //   let  index =item.departmentId;
      //   for (let i =0;i<this.departments.length; i++) {
      //    if(this.departments[i].id == index) {
      //      item.name = this.departments[i].name
      //      break
      //    }
      //   }
      // })
    },
    async getDeptAndCount(){
      const {data} = await findDeptAndCount()
      this.departments=data.data.departments
      sessionStorage.setItem("departments",JSON.stringify(this.departments))
    },

    //重置表单
    resetUserVo(){
      this.userVo.username = ''
      this.userVo.departmentId = ''
      this.userVo.email = ''
      this.userVo.nickname = ''
      this.userVo.sex= ''
      this.getUserList()
    },
    // 按钮点击事件 显示新增编辑弹窗组件
    show(){
      this.addOrUpdateVisible = true
    },
    // 监听 子组件弹窗关闭后触发，有子组件调用
    showAddOrUpdate(data){
      if(data === 'false'){
        this.addOrUpdateVisible = false
      }else{
        this.addOrUpdateVisible = true
      }
    },
    async exportExcel(){
      exportUserInfo(this.userVo).then(res => {
        //这里没有返回数据,但是要在响应头中进行下载操作
        // 将二进制文件转化为可访问的url
        let url = window.URL.createObjectURL(new Blob([res.data]));
        //创建了一个a标签的超链接
        var a = document.createElement("a");
        //将a标签添加到body内容中
        document.body.appendChild(a);
        a.href = url;
        a.download = "用户列表.xls";
        a.click();
        window.URL.revokeObjectURL(url);
      }).catch(err => {

      })
    },
    /**
     * 删除用户
     */
    async del(id) {
      var res = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(() => {
        this.$message({
          type: "info",
          message: "已取消删除"
        });
      });
      if (res == "confirm") {
        const { data: res } = await deleteUser (id)
        console.log(res);
        if (res.code == 200) {
          this.$notify.success({
            title:'操作成功',
            message:'用户删除成功',
          });
          this.getDeptAndCount();
          this.getUserList();
        } else {
          this.$message.error(res.msg);
        }
      }
    },
    /**
     * 用户信息详情
     */
    async edit(id) {
      const { data: res } = await userInfoDetail(id);
      if (res.code == 200) {
        console.log(res.data.userEditVO)
        this.editForm = res.data.userEditVO;
        this.editDialogVisible = true;
      } else {
        return this.$message.error("用户信息编辑失败:" + res.msg);
      }
    },
    /**
     * 关闭编辑弹出框
     */
    editClose() {
      this.$refs.editFormRef.clearValidate();
      this.editForm = {};
    },
    /**
     * 更新用户
     */
    async updateUser() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) {
          return;
        } else {
          this.btnLoading = true;
          this.btnDisabled = true;
          const { data: res } = await updateUserInfo(this.editForm);
          if (res.code == 200) {
            this.$notify({
              title: "操作成功",
              message: "用户基本信息已更新",
              type: "success"
            });
            this.editForm = {};
            this.getDeptAndCount();
            this.getUserList();
          } else {
            this.$message.error( res.message);
          }
          this.editDialogVisible = false;
          this.btnLoading = false;
          this.btnDisabled = false;
        }
      });
    },
    /**
     * 角色列表
     */
    async getRoleList(){
      this.size= 600;
      this.current= 1;
      const { data: res} = await  findRolePage(this.current,this.size,this.roleVo);
      if (res.code==200){
        console.log(res.data.roleList);
        this.data1=res.data.roleList;
      }else {
        this.$message.error( res.message);
      }
      this.size= 6;
      this.current= 1;
    },
    /**
     * 查询用户已经绑定的角色
     */
    async getRoleByUserId(id){
      const { data: res} = await getRoleByUserId(id)
      console.log(res.data.roleDetailByUserId)
      if (res.data.roleDetailByUserId !=null){
        this.value1=[res.data.roleDetailByUserId.id];
      }

    },
    /**
     * 弹出用户分配角色
     */
    async assignRoles(id) {
      console.log("需分配的用户的ID："+id)
      this.userRole.userId=id;
      this.data1=[];
      this.value1=[];
      this.getRoleList();
      this.getRoleByUserId(id);
      this.assignDialogVisible = true;
    },
    /**
     * 确认分配
     * @returns {Promise<void>}
     */
    async doAssignRoles(){
      if (this.userRole.roleId==''){
        this.$message.error( "请为用户分配一个角色");
      }else {
        console.log(this.userRole);
        const { data: res} =await bindUserRole(this.userRole)
        if (res.code=='200'){
          this.$notify.success({
            title: '操作成功',
            message: '分配角色成功',
          })
          this.assignDialogVisible = false;
          this.getUserList();
        }else {
          this.$message.error(res.message);
        }
      }
    },
    async  handleChange(value1) {
      if (value1.length==1){
        this.userRole.roleId=value1[0];
        console.log(this.userRole);
      }else if (value1.length==0){
        this.$message.error( "请添加一个用户角色");
      }else {
        this.$message.error( "只可添加一个用户角色");
      }
    }
  }
}
</script>

<style scoped>

</style>
